# -*- coding:utf-8 -*-
"""
识别某一祯的标题
@author: liandyao
@date: 2025/3/2 15:23
"""
import subprocess
import pytesseract
from PIL import Image

# 配置参数
video_path = r"G:\BaiduNetdiskDownload\少儿英语动画全集分级\熊出没大合集\TV版\2015 熊出没之冬日乐翻天（52集）1080P\熊出没之冬日乐翻天 E01.mp4"  # 输入视频路径
def extract_text_from_video(video_path,time_stamp="00:01:30"):
    """
    从视频中提取文字
    """
    output_image = "frame.jpg"  # 输出帧路径
    timestamp = time_stamp  # 截取时间点 (时:分:秒)
    tesseract_path = r"D:\Program Files\Tesseract-OCR\tesseract.exe"  # Tesseract安装路径

    # 设置Tesseract路径（根据实际安装位置修改）
    pytesseract.pytesseract.tesseract_cmd = tesseract_path

    # 步骤1：使用ffmpeg截取指定帧
    ffmpeg_cmd = [
        "ffmpeg","-y",
        "-ss", timestamp,  # 定位到指定时间
        "-i", video_path,  # 输入文件
        "-vframes", "1",  # 截取1帧
        "-q:v", "2",  # 输出质量（2-31，值越小质量越高）
        output_image
    ]

    try:
        subprocess.run(ffmpeg_cmd, check=True, capture_output=True)
    except subprocess.CalledProcessError as e:
        print(f"截取帧失败：{e.stderr.decode()}")
        exit(1)

    result = None
    # 步骤2：OCR识别文字
    try:
        # 预处理图像（可选增强识别效果）
        img = Image.open(output_image)

        # OCR识别
        text = pytesseract.image_to_string(img, lang='chi_sim+eng')  # 中英文识别
        text = text.replace(" ","")
        print("识别结果：", text)
        # 正则表达式匹配第三行
        lines = text.split("\n")
        if len(lines) >= 3:
            result = lines[1].strip()
            print("提取结果：", result)
            if result:
                print("识别结果：", result)
                return result
            else:
                return ""
        else:
            print("未找到第三行内容")
            return ""
        # print("识别结果：\n", text)

    except Exception as e:
        print(f"OCR识别失败：{str(e)}")
        return result
